<template>
  <div class="add-edit-content">
    <div class="hint-text">说明：{{ hintText }}</div>
    <avue-crud
      :option="options"
      v-model:search="search"
      v-model:page="page"
      v-model="form"
      :table-loading="loading"
      :data="data"
      :before-open="beforeOpen"
      ref="crud"
      @row-update="rowUpdate"
      @row-save="rowSave"
      @row-del="rowDel"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
    >
      <template #menu-left>
        <el-button type="success" plain :icon="FolderChecked" @click="handleImportCrf" v-if="getTrialStatus == '1'">{{
          btnText
        }}</el-button>
      </template>
    </avue-crud>
    <el-dialog v-model="isDialogStageCustom" :title="btnText" width="800">
      <div>
        <el-button type="success" plain :icon="FolderChecked" @click="handleEditCrf"
          >编辑CRF</el-button
        >
        <span>（可拖拽CRF，调整顺序）</span>
      </div>
      <div class="crf-content">
        <draggable
          v-model="crfList"
          item-key="id"
          group="parents"
          @end="handleParentDragEnd"
          class="parent-container"
        >
          <template #item="{ element: parent }">
            <div class="lord-content" :data-parent-id="parent.id">
              <span>{{ parent.crfName || parent.name }}</span>
            </div>
          </template>
        </draggable>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="isDialogStageCustom = false">关 闭</el-button>
          <el-button type="primary" @click="handleDialogSubmit"> 确 定</el-button>
        </div>
      </template>
    </el-dialog>
    <editCrf ref="editCrfRef" @changeCrfList="changeCrfList" />
  </div>
</template>
<script setup>
import editCrf from './editCrf.vue';
import { FolderChecked } from '@element-plus/icons-vue';
import {
  getList,
  getDetail,
  add,
  update,
  remove,
  lisWithSort,
  npOtherCrfSave,
  npOtherCrfRemove,
  npOtherCrfPage,
} from '@/api/group/group';
import { ref, reactive, computed, onMounted, defineEmits, watch, nextTick } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import option from '@/option/group/group';
import caseloadOptions from '@/option/caseload/caseload';
import { useRoute, useRouter } from 'vue-router';
const route = useRoute();
const emit = defineEmits();
const options = ref({
  height: 'auto',
  calcHeight: 30,
  tip: false,
  searchShow: true,
  searchMenuSpan: 6,
  border: true,
  index: true,
  viewBtn: true,
  selection: true,
  dialogClickModal: false,
  align: 'center',
  indexWidth: 80,
  indexLabel: '编号',
  addBtn: false,
  labelWidth: 145,
  addBtn: false,
  viewBtn: false,
  editBtn: false,
  column: [
    // {
    //   label: '编 号',
    //   prop: 'codeNumber',
    //   type: 'input',
    //   // rules: [{
    //   //   required: true,
    //   //   message: "请输入编号",
    //   //   trigger: "blur"
    //   // }],
    // },
    {
      label: 'CRF名称',
      prop: 'crfName',
      type: 'input',
    },
  ],
});
const form = ref({});
const routerQuery = ref({});
routerQuery.value = route.query;
const router = useRouter();
const crud = ref(null);
const store = useStore();
const query = ref({});
const search = ref({});
let loading = ref(false);
const page = ref({
  pageSize: 10,
  currentPage: 1,
  total: 0,
});
const selectionList = ref([]);
const data = ref([]);

let getTrialStatus = ref(localStorage.getItem('storageTrialStatus'));

let hintText = ref('');
let btnText = ref('');
let isDialogStageCustom = ref(false);
let editCrfRef = ref(null);
const props = defineProps({
  groupTab: {
    type: Number,
    default: 3,
  },
});
let sendEditCrfList = ref([]);
const initData = groupTab => {
  console.log(groupTab, props);
  hintText.value =
    groupTab === 3
      ? '此阶段用于配置入组前的纳排量表，可不进行配置！'
      : '此阶段用于配置其他定制的量表，可不进行配置！';
  btnText.value = groupTab === 3 ? '导入纳排CRF' : '导入其他定制表';
  options.value.menu = getTrialStatus.value == '1' ? true : false;
  refreshChange();
};
const crfList = ref();
// 导入按钮点击
const handleImportCrf = () => {
  isDialogStageCustom.value = true;
};
// 编辑CRF按钮点击
const handleEditCrf = () => {
  let editCrfForm = {
    isOpen: true,
    groupTab: props.groupTab,
    crfList: crfList.value || [],
  };
  nextTick(() => {
    editCrfRef.value.open(editCrfForm);
  });
};
// 弹窗确定按钮点击
const handleDialogSubmit = () => {
  let form = {
    groupId: routerQuery.value.groupId,
    type: props.groupTab === 3 ? '1' : '2',
  };
  // form.crf = crfList.value.map(item => ({ crf: item.id }));
  form.crfIds = crfList.value.map(item => item.crf).join(',');
  // form.crfIds = sendEditCrfList.value.map(item => (item.id)).join(',');
  npOtherCrfSave(form).then(res => {
    ElMessage({
      type: 'success',
      message: '操作成功!',
    });
    isDialogStageCustom.value = false;
    refreshChange();
  });
};
// 接收CRFList
const changeCrfList = list => {
  sendEditCrfList.value = [...list];
  /* 因为接收数据得到的id是crf的id，
    在这个页面获取的List中id是这条纳排记录的id，
    所以要将获得数据的id赋值给crf这个字段，
    以保证提交的时候，提交的是crf的id 
  */
  list.forEach(item => {
    if(!item.crf){
      item.crf = item.id;
    }
  });
  crfList.value = list;
  isDialogStageCustom.value = false;
  /* // 存放被删除的项的 id
  let deletedIds = [];
  // 遍历第一个数组，找出被删除的项
  crfList.value.forEach(item1 => {
    const isDeleted = !sendEditCrfList.value.some(item2 => item2.crf === item1.crf);
    if (isDeleted) {
      deletedIds.push(item1.crf); // 如果 item1 在 array2 中没有找到，则为删除的项，收集它的 id
    }
  });
  // 拼接成逗号分隔的字符串
  let deletedIdsString = deletedIds.join(',');
  if(deletedIdsString){
    npOtherCrfRemove(deletedIdsString);
    refreshChange();
  }else{
    console.log('这里美金吗');
    handleDialogSubmit();
  } */
  handleDialogSubmit();
};
// 拖拽结束事件
const handleParentDragEnd = (event, vm) => {
  console.log('拖拽结束', event.item._underlying_vm_);
};
watch(
  () => props.groupTab,
  (newValue, oldValue) => {
    initData(newValue);
  }
);
onMounted(() => {
  initData(props.groupTab);
});
const permission = computed(() => store.getters.permission);
const userInfo = computed(() => store.getters.userInfo);
// const validData = (value, defaultVal = false) => (value ? true : defaultVal);
// const permissionList = computed(() => ({
//   addBtn: validData(permission.value.group_add, false),
//   viewBtn: validData(permission.value.group_view, false),
//   delBtn: validData(permission.value.group_delete, false),
//   editBtn: validData(permission.value.group_edit, false),
// }));

// ids 计算属性
const ids = computed(() => {
  return selectionList.value.map(ele => ele.id).join(',');
});
const rowSave = (row, done, loading) => {
  add(row)
    .then(() => {
      // onLoad(page.value);
      refreshChange();
      ElMessage.success('操作成功!');
      done();
    })
    .catch(error => {
      loading();
      window.console.console.log(error);
    });
};

const rowUpdate = (row, index, done, loading) => {
  update(row)
    .then(() => {
      // onLoad(page.value);
      refreshChange();
      ElMessage.success('操作成功!');
      done();
    })
    .catch(error => {
      loading();
      window.console.console.log(error);
    });
};

const rowDel = row => {
  ElMessageBox.confirm('确定将选择数据删除?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      return npOtherCrfRemove(row.id);
    })
    .then(() => {
      // onLoad(page.value);
      refreshChange();
      ElMessage.success('操作成功!');
    });
};

const handleDelete = () => {
  if (selectionList.value.length === 0) {
    ElMessage.warning('请选择至少一条数据');
    return;
  }
  ElMessageBox.confirm('确定将选择数据删除?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      return remove(ids.value);
    })
    .then(() => {
      // onLoad(page.value);
      refreshChange();
      ElMessage.success('操作成功!');
    });
};

const beforeOpen = (done, type) => {
  if (['edit', 'view'].includes(type)) {
    getDetail(form.value.id).then(res => {
      form.value = res.data.data;
    });
  }
  done();
};

const searchReset = () => {
  query.value = {};
  // onLoad(page.value);
  refreshChange();
};

const searchChange = (params, done) => {
  query.value = params;
  page.value.currentPage = 1;
  // onLoad(page.value, params);
  refreshChange();
  done();
};

const selectionChange = list => {
  selectionList.value = list;
};

const selectionClear = () => {
  selectionList.value = [];
  crud.value.toggleSelection();
};

const currentChange = currentPage => {
  page.value.currentPage = currentPage;
};

const sizeChange = pageSize => {
  page.value.pageSize = pageSize;
};

const refreshChange = () => {
  let params = {
    type: props.groupTab === 3 ? '1' : '2',
    groupId: routerQuery.value.groupId,
    ...query.value,
  };
  onLoad(page.value, params);
};

const onLoad = (page, params) => {
  loading.value = true;
  let values = {
    descs: 'create_time',
    ...params,
  };
  npOtherCrfPage(page.currentPage, page.pageSize, values).then(res => {
    const DATA = res.data.data;
    page.total = DATA.total;
    data.value = DATA.records;
    crfList.value = DATA.records;
    // sendEditCrfList.value = DATA.records;
    loading.value = false;
    selectionClear();
  });
};
</script>
<style scoped>
.add-edit-content {
  width: 90%;
  height: 100%;
}
.hint-text {
  font-size: 16px;
  color: black;
  font-weight: 550;
  margin-bottom: 10px;
}
.crf-content {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
}
.parent-container {
  width: 60%;
  height: auto;
  padding: 0 12px;
  color: #3c8dbc;
  display: flex;
  flex-direction: column;
  align-items: center;
}
.lord-content {
  width: auto;
  min-width: 200px;
  height: auto;
  margin-bottom: 12px;
  cursor: pointer;
}
</style>